﻿class Vector {
	public var p:Point;

	public var dx:Number;
	public var dy:Number;

	public function Vector(p1:Point, x:Number, y:Number) {
		p = p1;

		dx = x;
		dy = y;
	}

	/*
	* GETTERS
	*/
	public function getLength():Number {
		return Math.sqrt(dx * dx + dy * dy);
	}
	public function getNormal():Vector {
		if (getLength() != 0) {
			var distx = dy / getLength();
			var disty = -dx / getLength();
			return new Vector(new Point(p.x + dx / 2, p.y + dy / 2), distx, disty);
		} else {
			return null;
		}
	}
	public function getAngle():Number {
		var ang = Math.atan2(dy, dx);
		return (ang);
	}
	public function getAngleDeg():Number {
		var ang = getAngle() * 180 / Math.PI;
		return (ang);
	}
	
	/*
	* SETTERS
	*/
	
	//make this Vector a copy of another
	public function copy(v:Vector):Void {
		p.x = v.p.x;
		p.y = v.p.y;
		
		dx = v.dx;
		dy = v.dy;
	}
	
	//set the start point
	public function setPoint(p1:Point):Void {
		p = p1;
	}
	
	//set dx, dy
	public function setXY(x:Number, y:Number):Void {
		dx = x;
		dy = y;
	}
	public function setAngle(a:Number):Void {
		var d = getLength();
		p.x = p.x + d * Math.cos(Math.PI * a / 180);
		p.y = p.y - d * Math.sin(Math.PI * a / 180);
	}
	
	public function setLength(dt:Number):Void {
		if (getLength != 0) {
			var ratio = dt / getLength();
			dx *= ratio;
			dy *= ratio;
		}
	}
	
	//swaps the start and endpoints
	public function reverse():Void {
		p.x += dx;
		p.y += dy;

		dx *= -1;
		dy *= -1;
	}
	
	//reverses the direction of the Vector with respect ro p
	public function reverseAng():Void {
		dx *= -1;
		dy *= -1;
	}

	public function normalize():Vector {
		if (getLength() != 0) {
			var newx = dx / getLength();
			var newy = dy / getLength();

			return new Vector(new Point(p.x, p.y), newx, newy);
		} else {
			return null;
		}
	}	
	
	/*
	* Mathematic Operations
	*/
	
	public function add(v:Vector):Vector {
		dx += v.dx;
		dy += v.dy;
		
		return this;
	}
	
	public function subtract(v:Vector):Vector {
		dx -= v.dx;
		dy -= v.dy;
		
		return this;
	}
	
	public function scalarMult(n:Number):Vector {
		dx *= n;
		dy *= n;
		
		return this;
	}
}